package com.spring.task;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;

import com.lmax.disruptor.EventHandler;
import com.spring.http.HttpContext;
import com.spring.http.HttpUtils;
import com.spring.http.ReturnData;
import com.spring.netty.HttpServerHandler;
import com.spring.remote.RemoteFactory;

public class TaskDispatcher {

	static Logger logger = LogManager.getLogger(TaskDispatcher.class.getName());

	private static TaskQueue requests = new TaskQueue();// 执行队列
	private static TaskQueue response = new TaskQueue();// 执行队列

	public static  void start() {
		try {
			// 监听消息队列任务并处理
			final EventHandler<TaskEvent> reqHandler = new EventHandler<TaskEvent>() {
				public void onEvent(final TaskEvent event, final long sequence, final boolean endOfBatch) throws Exception {
					try {
						logger.debug(event.getContext().getUri()+"请求的url");
						//执行拦截器
						List<Object> interceptor = RemoteFactory.interceptor(event.getContext(),"1");
						// 匹配url 和interceptor中的exclud
						boolean match = RemoteFactory.getMatch(interceptor,event.getContext());
						
						if(match) {
							RemoteFactory.getInvoke(event.getContext());
							return;
						}
						
						
						//需要拦截的url
						boolean applyPreHandle = RemoteFactory.applyPreHandle(event.getContext(), interceptor);
						if(applyPreHandle){
							List<Object> interceptorDesc = RemoteFactory.interceptor(event.getContext(),"2");
							RemoteFactory.getInvoke(event.getContext());
							RemoteFactory.afterCompletion(event.getContext(), interceptorDesc);
							
						}else{
							event.getContext().setRes(HttpUtils.errorSystem(ReturnData.getData(500, "对不起,系统已经拦截", null,"1")));
							HttpServerHandler.sendHttpResponse(event.getContext().getCtx(), event.getContext().getReq(),event.getContext().getRes());
						}
						
						
						
						
						// 执行方法
					} catch (Exception e) {
						logger.error("进入队列失败{0}",e);
						// 抛出异常
					}
				}

			};
			//响应结果队列 暂时不用
			final EventHandler<TaskEvent> resHandler = new EventHandler<TaskEvent>() {
				public void onEvent(final TaskEvent event, final long sequence, final boolean endOfBatch) throws Exception {
					try {
						// 执行方法
						logger.debug("响应队列");
						
						
						
						
						HttpServerHandler.sendHttpResponse(event.getContext().getCtx(), event.getContext().getReq(),event.getContext().getRes());
					} catch (Exception e) {
						logger.error("队列响应失败{0}",e);
						// 抛出异常
					}
				}

			};
			requests.setHandler(reqHandler);
			logger.info("开始启动队列");
			requests.start();
			response.setHandler(resHandler);
			response.start();
		} catch (Exception e) {
			logger.error("队列启动失败{0}",e);
		}
	}

	/**
	 * 
	 */
	public static void submitRequest(TaskEvent event) {
		requests.publish(event);
	}

	public static void submitReponse(TaskEvent event) {
		response.publish(event);
	}

}
